package com.sw.watcher;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.log4j.Logger;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.els.ElsConnection;
import com.els.factory.ElasticFactory;
import com.google.gson.JsonObject;
import com.sw.entity.Log;
import com.sw.imessage.SMS;

public abstract class BaseWatcher {
	protected Logger logger=Logger.getLogger(this.getClass());
	protected String url;
	protected int retryTime=3;
	protected String userAgent="Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36";
	protected int disputeId=1296;
	protected String token="systemwatch";

	protected HashMap<String, String> data=new HashMap<String, String>();
	protected String module;
	protected String sub_module;
	static SMS sms=new SMS();
	
	public int retryTime() {
		return retryTime;
	}
	public void retryTime(int retryTime) {
		this.retryTime = retryTime;
	}
	public String url() {
		return url;
	}
	public void url(String url) {
		this.url = url;
	}
	

	public boolean see() {
		Connection con = Jsoup.connect(url).userAgent(userAgent);
		con.data(data);
		Document doc=null;
		try {
			doc = con.get();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			logger.error(e.getMessage());
		}
		if(null==doc||"".equals(doc))
			return false;
		else
			return true;
	}
	public boolean watch(){
		boolean success=false;
		int retry=0;
		while(!success&&retry<retryTime){
			retry++;
			if(see()){
				success=true;
			}
		}
		return success;
	}
	public void run(){
		ElsConnection ec=ElasticFactory.getConnection();
		DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String now=df.format(new Date());
		boolean success=watch();
		Log log=new Log();
		log.setModule(module);
		log.setTime(now);
		log.setSub_module(sub_module);
		if(success){
			log.setRun(true);
			logger.info("["+module+"]["+sub_module+"]"+"运行正常。");
//			List<JsonObject> contacts = ec.queryAll("system", "notice");
//			for (JsonObject obj : contacts) {
//				if(obj.get("active").getAsBoolean()){
//					sms.warning(obj.get("tel").getAsString(), module, sub_module);
//					logger.info("发送短信给用户："+obj.toString());
//				}
//			}
		}else{
			//发送通知
			log.setRun(false);
			log.setRemark("失败!");
			logger.error("["+module+"]["+sub_module+"]"+"运行失败！");
			List<JsonObject> contacts = ec.queryAll("system", "notice");
			for (JsonObject obj : contacts) {
				if(obj.get("active").getAsBoolean()){
					sms.warning(obj.get("tel").getAsString(), module, sub_module);
					logger.info("发送短信给用户："+obj.toString());
				}
			}
		}
		ec.insertOne("log", "log", null, log.json());
	}
	
}
